import React, { useEffect, useMemo, useRef, useState } from "react";
import { Input, Tree, Checkbox, Space, Button } from "antd";
import { SearchOutlined } from "@ant-design/icons";
import { searchTree, TreeToArray } from "@/utils";

export const TreeWarpper = (props) => {
  const {
    inputWarpper,
    initTreeData = [],
    checkable = false,
    selectable = false,
    toggleAll,
    defaultCheckKeys = [], // 默认选中的节点
    defaultSelectKeys = [],
    defaultExpandedKeys = [], // 默认展开的节点
    showLine,
    defaultExpandAll,
    onHandleSelect,
    onHandleCheckAllChange,
    width = '600px',
    height = 0,
    menuTreeSlot = false,
    menuTreeNode = () => {},
  } = props;
  const [treeData, setTreeData] = useState([]);
  const [defaultData, setDefaultData] = useState([]);
  const [checkedKeys, setCheckedKeys] = useState<React.Key[]>([]);
  const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);
  const [checkAll, setCheckAll] = useState(false);
  const [indeterminate, setIndeterminate] = useState(false);
  const [arrList, setArrList] = useState([]); // 存储拆分树结构的普通数组
  useEffect(() => {
    const data = JSON.parse(JSON.stringify(initTreeData)) || [];
    const list = TreeToArray(data);
    setArrList(list);
    setTreeData(data);
    setDefaultData(data);
    setCheckedKeys(defaultCheckKeys);
    setSelectedKeys(defaultSelectKeys);

    checkAllNodes(defaultCheckKeys, list);
    if (defaultCheckKeys.length) {
      let newList = [];
      list.forEach((item) => {
        defaultCheckKeys.forEach((it) => {
          if (item.key == it) {
            newList.push(item);
          }
        });
      });
      onHandleCheckAllChange(defaultCheckKeys, newList);
    }
  }, []);

  const onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { value } = e.target;
    if (!value) return setTreeData(defaultData);
    const newExpandedKeys = searchTree(defaultData, value, true);

    setTreeData(newExpandedKeys);
  };

  const onCheckAllChange = (e) => {
    setCheckAll(e.target.checked);
    const data = e.target.checked ? getAllKeys() : [];
    console.log("data", data);
    setCheckedKeys(data);
    checkAllNodes(data, arrList);
    onHandleCheckAllChange(data, data.length ? arrList : []);
  };

  const onCheck = (checkedKeysValue, e) => {
    setCheckedKeys(checkedKeysValue);
    checkAllNodes(checkedKeysValue, arrList);
    onHandleCheckAllChange(checkedKeysValue, e.checkedNodes);
  };

  const onSelect = (selectedKeysValue, info) => {
    setSelectedKeys(selectedKeysValue);
    onHandleSelect(selectedKeysValue, info);
  };

  function checkAllNodes(checkedList, originalList) {
    setIndeterminate(
      !!checkedList.length && checkedList.length < originalList.length
    );
    setCheckAll(checkedList.length === originalList.length);
  }

  // 获取所有key
  function getAllKeys() {
    let result = [];
    function fn(target) {
      let arr = target.reduce((pre, item) => {
        if (Array.isArray(item.children) && item.children.length) {
          return [...pre, item.key, ...fn(item.children)];
        }
        return [...pre, item.key];
      }, []);
      return arr;
    }
    result = fn(treeData);
    return result;
  }

  const customTreeTitle = {
    flex: "1",
  };

  const menuTree = (data) => {
    if (menuTreeNode()) {
      return menuTreeNode(data);
    } else {
      return (
        <Space
          style={{
            marginLeft: "10px",
          }}
        >
          <a onClick={(e) => handleTreeAdd(data)} style={{ color: "#1677ff" }}>
            新增
          </a>
          <a onClick={(e) => handleTreeEdit(data)} style={{ color: "#1677ff" }}>
            编辑
          </a>
          <a onClick={(e) => handleTreeDel(data)} style={{ color: "#ff4D4F" }}>
            删除
          </a>
        </Space>
      );
    }
  };

  const handleTreeAdd = (data) => {
    // console.log("handleTreeAdd", data);
  };
  const handleTreeEdit = (data) => {
    // console.log("handleTreeEdit", data);
  };
  const handleTreeDel = (data) => {
    // console.log("handleTreeDel", data);
  };

  // const handleStop = (e) => {
  //   e.stopPropagation()
  // }

  return (
    <div className="tree">
      {inputWarpper && (
        <Input
          prefix={<SearchOutlined />}
          allowClear
          style={{ marginBottom: 8 }}
          placeholder="Search"
          onChange={onChange}
        />
      )}

      <div className="head-container">
        {toggleAll && (
          <Checkbox
            style={{ margin: "6px 24px" }}
            indeterminate={indeterminate}
            onChange={onCheckAllChange}
            checked={checkAll}
          >
            全选
          </Checkbox>
        )}
        {treeData.length > 0 && (
          <Tree
            height={height}
            selectable={selectable}
            selectedKeys={selectedKeys}
            checkedKeys={checkedKeys}
            checkable={checkable}
            treeData={treeData}
            onCheck={onCheck}
            onSelect={onSelect}
            showLine={showLine}
            defaultExpandAll={defaultExpandAll}
            defaultExpandedKeys={defaultExpandedKeys}
            titleRender={(nodeData) => (
              <div
                style={{
                  display: "flex",
                  justifyContent: "space-between",
                  alignItems: "center",
                  width: width,
                }}
              >
                <span style={customTreeTitle}>{nodeData.title}</span>
                <div onClick={(e) => e.stopPropagation()}>
                  {menuTreeSlot && menuTree(nodeData)}
                </div>
              </div>
            )}
          />
        )}
      </div>
    </div>
  );
};

export default TreeWarpper;
